const express = require('express')
const svg2img = require('svg2img');
const svgCaptcha = require('svg-captcha')
const models = require('../models/models')
const router = express.Router()
const fs = require('fs')
const path = require('path')
    //导入文件上传的中间件
const multiparty = require('connect-multiparty')
const multipartMiddleware = multiparty() //获取一个文件上传中间件对象



//获取验证码
router.get('/captcha', function(req, res) {
    // 生成随机字符串
    const captcha = svgCaptcha.create();
    // 保存验证码信息到 session 中
    req.session.captcha = captcha.text;
    svg2img(captcha.data, { format: 'png' }, function(error, buffer) {
        if (error) {
            console.log('SVG 转 PNG 失败：', error);
        } else {
            let bufferimg = Buffer.from(buffer)
            var base64Str = bufferimg.toString('base64')
                // 将 buffer 保存为 PNG 文件
            res.send({
                data: {
                    code: 200,
                    msg: '获取成功',
                    img: 'data:image/png;base64,' + base64Str,
                    captcha: captcha.text
                }
            })
        }
    });

})

//登录
router.post('/login', function(req, res) {
    const userInputCaptcha = req.body.captcha;
    let { username, password } = req.body
    let date = [username, password]
    models.login(date).then(value => {
        if (value.length > 0) {
            res.send({
                data: {
                    code: 200,
                    msg: '登录成功',
                    token: req.sessionID,
                    realname: value[0].realname,
                    role: value[0].role,
                    avatar: value[0].avatar
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: '登录失败'
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })

})

//查询商品
router.post('/srrgoodsforpage', function(req, res) {
    let { pageNum } = req.body
    if (isNaN(pageNum)) {
        res.send({
            data: {
                code: 406,
                msg: '页码有误'
            }

        })
    } else if (Number(pageNum) < 1) {
        res.send({
            data: {
                code: 406,
                msg: '页码不能为负数'
            }

        })
    } else {
        let pageNumber = Number(pageNum) //获取页码
        let pageSize = Number(req.body.pageSize) //获取一页多少条
        models.selectrrgoods().then(value => {
            let pageCount = Math.ceil(value.length / pageSize); //总页数 
            let data = [
                (pageNumber - 1) * pageSize, //第一个问号的值
                pageSize
            ]
            models.srrgoodsforpage(data).then(value2 => {
                if (value2.length > 0) {
                    value2.forEach(item => {
                        item.goodsimg = item.goodsimg.split(',')
                    });
                    res.send({
                        data: {
                            code: 200,
                            msg: '查询成功',
                            rrgoods: value2,
                            pageCount: pageCount,
                            pageNumber: pageNumber
                        }
                    })
                } else {
                    res.send({
                        data: {
                            code: 201,
                            msg: '查询失败'
                        }
                    })
                }
            }, reason => {
                res.send({
                    reason
                })
            })

        }, reason => {
            res.send({
                reason
            })
        })
    }

})

//上传图片
router.post('/uploading', multipartMiddleware, (req, res) => {
    //将文件写入到服务器指定目录(实际是拷贝的过程)
    fs.readFile(req.files.files.path, 'binary', function(err, datastr) {
            if (err) {
                res.send({
                    data: {
                        code: 204,
                        msg: "读取文件失败"
                    }
                })
            } else {
                let imgpath = path.join(__dirname, '../public/images', 'uploads') + "/" + req.files.files.name
                fs.writeFile(imgpath, datastr, 'binary', (err) => {
                    if (err) {
                        res.send({
                            data: {
                                code: 204,
                                msg: "写入文件失败"
                            }
                        })
                    } else {
                        let imgurl = "http://127.0.0.1:3050/" + req.files.files.name
                        res.send({
                            data: {
                                code: 200,
                                msg: "上传成功",
                                imgurl: imgurl
                            }
                        })
                    }
                })
            }
        })
        // console.log('文件上传成功');

})

//新增商品
router.post('/addrrgoods', function(req, res) {
    let { goodsname, goodsimg, price, tag } = req.body
    let data = [goodsname, goodsimg, price, tag]
    models.addrrgoods(data).then(value => {
        if (value.affectedRows > 0) {
            res.send({
                data: {
                    code: 200,
                    msg: "添加成功"
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "添加失败"
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })
})

//编辑商品
router.post('/updategoods', function(req, res) {
    let { goodsname, goodsimg, price, tag, id } = req.body
    let data = [goodsname, goodsimg, price, tag, id]
    models.updategoods(data).then(value => {
        if (value.affectedRows > 0) {
            res.send({
                data: {
                    code: 200,
                    msg: "编辑成功",
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "编辑失败"
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })
})

//删除商品
router.post('/deleterrgoods', function(req, res) {
    let { id } = req.body
    let data = [id]
    models.deleterrgoods(data).then(value => {
        if (value.affectedRows > 0) {
            res.send({
                data: {
                    code: 200,
                    msg: "删除成功",
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "删除失败"
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })
})


//删除多见商品
router.post("/deleteMorerrgoods", function(req, res) {
    let data = req.body
    if (!Array.isArray(data)) {
        res.send({
            data: {
                status: 0,
                message: '必须是数组'
            }
        })
    } else if (data == '') {
        res.send({
            data: {
                status: 0,
                message: '参数不能为空'
            }
        })
    } else {
        models.deleteMorerrgoods(data).then(value => {
            if (value.affectedRows > 0) {
                res.send({
                    data: {
                        code: 200,
                        msg: "删除成功"
                    }
                })
            } else {
                res.send({
                    data: {
                        code: 201,
                        msg: "删除失败"
                    }
                })
            }
        }, reason => {
            res.send({
                reason
            })
        })
    }
})

//查询累计销量
router.get('/searchsalescount', function(req, res) {
    models.searchsalescount().then(value => {
        if (value.length > 0) {
            res.send({
                data: {
                    code: 200,
                    salescount: value[0].salescount,
                    msg: "ok"
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "查询失败"
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })
})

//查询各商品的销量
router.get('/searchgoodssales', function(req, res) {
    models.searchgoodssales().then(value => {
        if (value.length > 0) {
            res.send({
                data: {
                    code: 200,
                    data: value,
                    msg: "ok"
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "查询失败"
                }
            })
        }
    })
})

//购买商品
router.post('/buygoods', function(req, res) {
    let { id } = req.body
    let data = [id]
    models.buygoods(data).then(value => {
        if (value.affectedRows > 0) {
            res.send({
                data: {
                    code: 200,
                    msg: "购买成功"
                }
            })
        } else {
            res.send({
                data: {
                    code: 201,
                    msg: "购买失败"
                }
            })
        }
    }, reason => {
        res.send({
            reason
        })
    })
})



module.exports = router